package com.demo.spring_demo.controller.login;

import com.demo.spring_demo.mapper.UserMapper;
import com.demo.spring_demo.pojo.Result;
import com.demo.spring_demo.pojo.User;
import com.demo.spring_demo.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@CrossOrigin
public class LoginController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    Utils utils;

    @PostMapping("/login")
    public Result login( @RequestBody User user, HttpSession session,HttpServletRequest request, HttpServletResponse response) {
        //登录操作判断是否登录成功!
        if(userMapper.login(user) != null) {

            //1、发送cookie
            utils.sendCookie(user,request,response);

            //发送session数据
            request.getSession().setAttribute("userLogin", user.getUsername());

            if("root".equals(user.getUsername())){
                return new Result(200,user,"root_success"); //管理员界面
            }else {
                return new Result(200,user,"user_success"); //普通用户界面
            }

        }else {
            return new Result(500,"用户名或密码有误！");
        }
    }



}
